import logging
import os
import sys
import pandas as pd
sys.path.append("..")
from MAPPING import list_file


# 本文件作用是统计正确率
# 输入文件要求xlsx格式文件，切文件应在该目录下
# 表格须有Sheet1工作簿，且第一行为表头
# 表必须有“头实例”，“尾实例”，“类型”，“标注”四个列

def process_row(df):
    tmp = {
        "记录数": 0,
        "ok":0
    }
    for index, row in df.iterrows():
        if type(row['标注']) is str:
            row['类型'] = str(row['类型'])
            tmp['记录数'] += 1
            if row['类型'] not in tmp.keys():
                tmp[row['类型']] = 0
                tmp["c"+row['类型']] = 0
            tmp["c"+row['类型']] += 1
            if row['标注'].lower() == "ok":
                tmp['ok'] += 1
                tmp[row['类型']] += 1
            else:
                logSTATIC.info('%s\t%s\t%s\t%s'%(row['头实例'],row['尾实例'],row['类型'],row['标注']))
    return tmp


def map_file(pathBase, fileList):
    tmpList = []
    for i in range(0, len(fileList)):
        if fileList[i][0]== '~':
            continue
        logSTATIC.debug('第%d个文件' % i)
        file = os.path.join(pathBase, fileList[i])
        pd.set_option('display.max_columns', 1000)
        pd.set_option('display.max_rows', None)
        df = pd.read_excel(file, sheet_name="Sheet1")
        t = process_row(df[['头实例','尾实例','类型','标注']])
        logSTATIC.info(t)
        tmpList.append(t)
    result = {}
    for t in tmpList:
        for k,v in t.items():
            if k not in result.keys():
                result[k] = v
            else:
                result[k] += v
    logSTATIC.info(result)
    return result


def compute(res):
    print("============================================")
    print('标注记录数\t%d'%res['记录数'])
    print('ok数\t%d'%res['ok'])
    print("总正确率（ok数/标注记录数）：%f"%(res['ok']/res['记录数']))
    print("++++++++++++++++++++类别明细+++++++++++++++++++++")
    for k,v in res.items():
        if k == "记录数" or k == "ok" or k[0] == 'c':
            continue
        print("[%s]记录数\t%d"%(k,res['c'+k]))
        print("[%s]ok数\t%d"%(k,res[k]))
        print("[%s]正确率\t%f"%(k,res[k]/res['c'+k]))
        print("+++++++++++++++++++++++++++++++++++++++++++++")
    print("============================================")



def main():
    fileList = list_file("./", ".xlsx")
    fileListSize = len(fileList)
    print("共找到%d个文件" % fileListSize)
    for i in range(0, 9 if 9 < fileListSize else fileListSize):
        print(fileList[i])
    print("...")
    r = map_file("./",fileList)
    compute(r)



if __name__ == '__main__':
    logSTATIC = logging.getLogger("STATIC")
    logSTATIC.setLevel(logging.DEBUG)
    hdSTATIC = logging.FileHandler("STATIC.log", mode='w', encoding='utf-8')
    hdSTATIC.setLevel(logging.DEBUG)
    logSTATIC.addHandler(hdSTATIC)
    main()